# coding=utf-8
# 这是一个海兴645维护协议，实现抄读指定fd空间的功能

def str_to_int(data):
    value = 0
    for j in range(len(data)):
        if "0" <= data[j] <= "9":
            value += ord(data[j]) - ord("0")
        else:
            return 0
        value *= 10
    value /= 10
    return value


def str_to_hex(data):
    value = 0
    for j in range(2):
        if "0" <= data[j] <= "9":
            value += ord(data[j]) - ord("0")
        elif "A" <= data[j] <= "Z":
            value += ord(data[j]) - ord("A") + 10
        elif "a" <= data[j] <= "z":
            value += ord(data[j]) - ord("a") + 10
        else:
            return 0
        value *= 16
    value /= 16
    return value


def dlt645_add_33(source_data):
    return hex(str_to_hex(source_data) + 0x33)[-2:]


def check_sum(source):
    sum = 0
    for i in range(0, len(source), 2):
        sum += str_to_hex(source[i:i + 2])
    return hex(sum)[-2:]


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    input_file = open("./input_info.txt", "r", buffering=-1)
    address = input_file.readline().rstrip("\n")
    fs_id = input_file.readline().rstrip("\n")
    offset = str_to_int(input_file.readline().rstrip("\n"))
    length = str_to_int(input_file.readline().rstrip("\n"))
    input_file.close()

    # 测试数据
    step = 0xC0  # 循环抄读步进 19
    zone = 0  # 主区数据
    # address = "010203040506"
    # fs_id = "F908"  # 数据fd
    # offset = 0x1000  # 数据便宜
    # length = 4096  # 抄读数据长度

    frame_text = "68"
    for i in range(5, -1, -1):
        frame_text += address[i * 2:(i + 1) * 2]
    frame_text += "68" + "05" + "08"
    for i in range(1, -1, -1):
        frame_text += dlt645_add_33(fs_id[i * 2:(i + 1) * 2])
    if zone == 0:
        frame_text += dlt645_add_33("00")
    else:
        frame_text += dlt645_add_33("01")

    while length:
        temp = "00000000" + hex(offset)[2:]
        if len(temp) % 2 == 1:
            temp = "0" + temp
        for i in range((len(temp)) / 2 - 1, (len(temp) / 2) - 5, -1):
            frame_text += dlt645_add_33(temp[i * 2:(i + 1) * 2])

        if length > step:
            frame_text += dlt645_add_33(hex(step)[2:])
            offset += step
            length -= step
        else:
            frame_text += dlt645_add_33(hex(length)[2:])
            length = 0

        frame_text += check_sum(frame_text)
        frame_text += "16"
        # 字节间不加空格输出
        # print frame_text
        # 字节间加空格输出
        for index in range(0, len(frame_text), 2):
            print frame_text[index:index + 2],
        print ""

        # 输出到read_frame
        output_file = open("./read_frame.txt", "a", buffering=-1)
        output_file.writelines(frame_text.upper() + "\n")
        frame_text = "" + frame_text[0:26]
    output_file.writelines('\n')
    output_file.close()
